package org.yoao.moneymachine.business.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.yoao.crm.struts.form.OrderForm;
import org.yoao.crm.tools.CodeFactory;
import org.yoao.moneymachine.bean.Order;
import org.yoao.moneymachine.business.service.IOrderService;
import org.yoao.moneymachine.dao.OrderDAO;
import org.yoao.moneymachine.dao.UserDAO;

/**
 * @author Weishion.Yi
 * @description
 * @date 2010-10-5 下午02:46:04
 */
public class OrderServiceImpl implements IOrderService {
	private OrderDAO orderDAO = new OrderDAO();
	private UserDAO userDAO = new UserDAO();

	public int getDataCount(Map map) throws Exception {
		return orderDAO.getDataCount(map);
	}

	public List view(int startRow, int endRow, Map map) throws Exception {
		return orderDAO.find(startRow, endRow, map);
	}

	public void action(String id, String value) throws Exception {
		if (id.endsWith(","))
			id = id.substring(0, id.length() - 1);
		if("3".equals(value)){
			orderDAO.modifyStatus(id, value);
			return;
		}
		String[] idArray = id.split(",");
		if (idArray != null && idArray.length > 0) {
			for (int i = 0; i < idArray.length; i++) {
				Order order = orderDAO.findById(idArray[i]);
				if (order == null || order.getStatus().equals(value))
					continue;
				Map map = orderDAO.findPayById(idArray[i]);
				String expandCode = (String) map.get("EXPANDCODE");
				String price = (String) map.get("PRICE");
				String amount = (String) map.get("AMOUNT");
				if (price == null || price.trim().equals(""))
					price = "0.00";
				if (amount == null || amount.trim().equals(""))
					amount = "0.00";
				if (map != null && !map.isEmpty()) {
					orderDAO
							.modifyUserAmountTotal(expandCode, 1, Float
									.parseFloat(amount), Float
									.parseFloat(price), value);
					orderDAO.modifyStatus(idArray[i], value);
				}
			}
		}
	}

	public void delete(String id) throws Exception {
		if (id.endsWith(","))
			id = id.substring(0, id.length() - 1);
		orderDAO.delete(id);
	}

	@Override
	public OrderForm add(OrderForm form) throws Exception {
		form.setOrderNumber(CodeFactory.getOrderNumberBySQL());
		Order order = new Order();
		BeanUtils.copyProperties(order, form);
		if (orderDAO.insert(order) > -1) {
			form.setInfo("订单生产成功!");
		} else {
			form.setInfo("订单生产失败!");
		}
		return form;
	}

	@Override
	public boolean modify(String id, String memo) throws Exception {
		Order order = new Order();
		order.setId(id);
		order.setMemo(memo);
		if(orderDAO.modifyMemo(order) > -1)
			return true;
		else return false;
	}
}